package net.caidingke.shepherd.profile;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Validate;
import org.springframework.context.ApplicationContext;

/**
 * SpringContextHolder
 *
 * @author bowen
 */
@Slf4j
public class SpringContextHolder {

    private static ApplicationContext context;

    public static <T> T getBean(Class<T> clazz) {
        try {
            return context.getBean(clazz);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        Validate.validState(context != null, "applicationContext no injection");
        return context;
    }
}
